"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const alidns20150109_1 = __importStar(require("@alicloud/alidns20150109")), $Alidns20150109 = alidns20150109_1;
const $OpenApi = __importStar(require("@alicloud/openapi-client"));
const $Util = __importStar(require("@alicloud/tea-util"));
const node_schedule_1 = __importDefault(require("node-schedule"));
const server = (0, express_1.default)();
server.use(express_1.default.json());
server.use(express_1.default.urlencoded({ extended: false }));
let tempIp = undefined;
server.get("/", (req, res) => {
    if (tempIp === undefined) {
        res.status(500).send("Get Records Fail, See Container Logs.");
    }
    else {
        res.send(tempIp);
    }
});
server.listen(16602, () => {
    console.log("Server is Running At Port 16602");
});
const accessKeyId = process.env.ACCESS_KEY_ID;
const accessKeySecret = process.env.ACCESS_KEY_SECRET;
const domain = process.env.ALIDNS_DOMAIN;
const interval = process.env.INTERVAL;
console.log(`${new Date().toLocaleString()} Setting: accessKeyId: ${accessKeyId} accessKeySecret: ${accessKeySecret} domain: ${domain} interval: ${interval}`);
//每隔多少分钟运行一次
node_schedule_1.default.scheduleJob(`0 */${interval} * * * *`, () => __awaiter(void 0, void 0, void 0, function* () {
    getRecords(accessKeyId, accessKeySecret, domain).then((data) => {
        console.log(`${new Date().toLocaleString()}  Get IP Record Success:${data}`);
        tempIp = data;
    }).catch((err) => {
        console.log(`${new Date().toLocaleString()}  Get IP Record Fail:${err}`);
        tempIp = undefined;
    });
}));
function getRecords(accessKeyId, accessKeySecret, domain) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise((resolve, reject) => {
            try {
                let config = new $OpenApi.Config({
                    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                    accessKeyId: accessKeyId,
                    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                    accessKeySecret: accessKeySecret,
                });
                // Endpoint 请参考 https://api.aliyun.com/product/Alidns
                config.endpoint = `alidns.cn-hangzhou.aliyuncs.com`;
                const client = new alidns20150109_1.default(config);
                let describeDomainRecordsRequest = new $Alidns20150109.DescribeDomainRecordsRequest({
                    domainName: domain,
                });
                client.describeDomainRecordsWithOptions(describeDomainRecordsRequest, new $Util.RuntimeOptions({})).then(res => {
                    var _a, _b;
                    let records = (_b = (_a = res.body) === null || _a === void 0 ? void 0 : _a.domainRecords) === null || _b === void 0 ? void 0 : _b.record;
                    if (records === undefined) {
                        reject("No Records Found");
                    }
                    else {
                        let found = false;
                        for (const record of records) {
                            if (record.domainName == domain) {
                                found = true;
                                resolve(record.value);
                            }
                        }
                        if (!found) {
                            reject("No Records Found");
                        }
                    }
                }).catch((err) => {
                    reject(err.message);
                });
            }
            catch (e) {
                reject(e.message);
            }
        });
    });
}
